<!--
* description: 备件销售审核
* author: ligy
* createdDate: 2021-3-2
-->
<template>
  <div class="app-container app-container-table">
    <!-- 单表格模版页面 -->
    <div>
      <el-row style="margin-top:1rem" :gutter="5">
        <el-col :span="14">
          <one-table-template
            ref="multipleTable"
            :dynamic-api-config="apiConfig"
            :dynamic-buttons="dynamicButtons"
            :dynamic-components="tableComponents"
            :dynamic-table-cols="dynamicTableCols"
            :dynamic-form-fields="formField"
            :dynamic-is-show-more-btn="false"
            :dynamic-is-show-select="true"
            :dynamic-is-init-table="false"
            :is-show-pagination="false"
            :callback-obj="callbackObj1"
          />
        </el-col>
        <el-col :span="10">
          <div class="custom-title">
            <span class="blabel">网点名称：</span><span class="left">{{ item.dlrShortName }}</span>
            <span class="blabel">汇总金额：</span><span class="center">{{ item.billAmount ? '￥'+ item.billAmount : '' }}</span>
            <!--            <el-button class="right el-button el-button&#45;&#45;small" @click="unSettlemen()">审核</el-button>-->
          </div>
          <one-table-template
            ref="multipleTable1"
            :dynamic-api-config="apiConfig1"
            :dynamic-buttons="dynamicButtons1"
            :dynamic-table-cols="dynamicTableCols1"
            :dynamic-form-fields="formField1"
            :dynamic-table-defult-height="290"
            :dynamic-is-show-more-btn="false"
            :dynamic-is-show-select="false"
            :is-show-pagination="false"
            :callback-obj="callbackObj2"
          />
          <one-table-template
            ref="multipleTable2"
            :dynamic-api-config="apiConfig2"
            :dynamic-buttons="dynamicButtons2"
            :dynamic-table-cols="dynamicTableCols2"
            :dynamic-form-fields="formField2"
            :dynamic-table-defult-height="290"
            :dynamic-is-show-more-btn="false"
            :dynamic-is-show-select="false"
            :is-show-pagination="false"
          />
        </el-col>
      </el-row>
    </div>
  </div>
</template>
<script>
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import Vue from 'vue'
import { orgApis } from '@/api/paSparePartsManagement'
export default {
  name: 'SparePartsSalesReverseSettlement',
  components: {
    OneTableTemplate
  },
  mixins: [oneTableWithViewTemplateMixins],
  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData(
      // 同时加载当前页面和编辑框页面的配置
      [to.path, ''],
      function() {
        next()
      }
    )
  },
  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path
    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])
    return {
      selectiondata: [],
      carConfigId: '',
      editData: {},
      titleName: '新增选装包',
      name: '',
      // id: '',
      item: {},
      dialogShow: false,
      editPopupsState: 'add',
      //   editRowData: {},
      // table表格查询API配置对象
      apiConfig: orgApis.statistical,
      apiConfig1: orgApis.orderDetails,
      apiConfig2: orgApis.partDetails,
      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableComponents
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode]
            .tableComponents
          : [
            {
              compKey: 'compKey1',
              labelName: '网点编码：',
              codeField: 'dlrShortName',
              textField: 'dlrCode',
              component: () => import('@/views/ve/planReport/components/multipleSearchInput'),
              type: 'inputText',
              isMust: true,
              dataToObject: {
                oFields: 'dlrShortName,dlrCode',
                // 控制弹窗页面 搜索 网格 元素
                tableComponents: [
                  {
                    compKey: 'compKey1',
                    labelName: '网点编码：',
                    codeField: 'dlrCode',
                    component: () => import('@/components/org/commonInput'),
                    type: 'inputText',
                    isMust: true,
                    span: 8
                  },
                  {
                    compKey: 'compKey2',
                    labelName: '网点名称：',
                    codeField: 'dlrShortName',
                    component: () => import('@/components/org/commonInput'),
                    type: 'inputText',
                    isMust: true,
                    span: 8
                  }
                ],
                tableCols: [
                  {
                    prop: 'dlrCode',
                    label: '网点编码'
                  },
                  {
                    prop: 'dlrShortName',
                    label: '网点名称'
                  }
                ],
                formField: {
                  dlrShortName: '',
                  dlrCode: ''
                },
                returnField: {
                  prop: 'dlrCode',
                  label: '网点编码'
                },
                api: orgApis.queryOrgDlrCodes
              },
              span: this.spanNum()
            },
            {
              compKey: 'compKey2',
              labelName: '网点名称：',
              codeField: 'dlrShortName',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              span: this.spanNum()
            },
            {
              compKey: 'compKey3',
              labelName: '出库单号：',
              codeField: 'outCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              span: this.spanNum()
            },
            {
              compKey: 'compKey4',
              labelName: '结算日期：',
              codeField: 'startDate,endDate',
              component: () => import('@/components/org/datePicker/andtDatePicker'),
              type: 'YYYY-MM-DD',
              format: 'yyyy-MM-dd',
              dateOptionsType: '0',
              isMul: false,
              isMust: true,
              span: this.spanNum()
            }
          ],
      // form 的表单对象
      formField: {
        dlrCode: '',
        dlrShortName: '',
        outCode: '',
        startDate: '',
        endDate: '',
        lumpSum: ''
      },
      // 动态组件-按钮
      dynamicButtons:
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons
          : [
            {
              compKey: 'btnKey1',
              type: 'primary',
              size: 'small',
              name: 'search',
              clickEvent: () => this.queryTable(1),
              text: '查询'
            },
            {
              compKey: 'btnKey2',
              type: '',
              size: 'small',
              name: 'examine',
              clickEvent: () => {
                // mp/e3sh/spareparts/finance/countersettlementSparePartsSalesService/billPass.do
                if (!this.selectiondata.length) return this.$message('请至少勾选一条数据!')
                const loading = this.$loading({ text: `请稍等...` })
                this.$requestAPI({
                  apiUrl: 'mp/e3sh/spareparts/finance/countersettlementSparePartsSalesService/billPass.do',
                  variables: this.selectiondata.map(o => ({ billOrderId: o['billOrderId'] }))
                }).then(res => {
                  if (res.result === '1') {
                    this.$message(res.msg || '审核通过!')
                    this.$refs['multipleTable'].queryTable()
                    this.resetData()
                  } else {
                    this.$message(res.msg || '审核失败!')
                  }
                }).catch(err => {
                  if (err.response.data.msg) {
                    this.$message(err.response.data.msg)
                  } else {
                    this.$message(err.message)
                  }
                }).finally(() => {
                  loading.close()
                })
              },
              text: '审核通过'
            },
            {
              compKey: 'btnKey2',
              type: '',
              size: 'small',
              name: 'reject',
              clickEvent: () => {
                //  /mp/e3sh/spareparts/finance/countersettlementSparePartsSalesService/antiSettlement.do
                if (!this.selectiondata.length) return this.$message('请至少勾选一条数据!')
                const loading = this.$loading({ text: `正在驳回,请稍等...` })
                this.$requestAPI({
                  apiUrl: '/mp/e3sh/spareparts/finance/countersettlementSparePartsSalesService/antiSettlement.do',
                  variables: this.selectiondata.map(o => ({ billOrderId: o['billOrderId'] }))
                }).then(res => {
                  if (res.result === '1') {
                    this.$message(res.msg || '驳回成功!')
                    this.$refs['multipleTable'].queryTable()
                    this.resetData()
                  } else {
                    this.$message(res.msg || '驳回失败!')
                  }
                }).catch(err => {
                  if (err.response.data.msg) {
                    this.$message(err.response.data.msg)
                  } else {
                    this.$message(err.message)
                  }
                }).finally(() => {
                  loading.close()
                })
              },
              text: '驳回'
            },
            {
              compKey: 'btnKey4',
              type: '',
              size: 'small',
              name: 'reset',
              clickEvent: () => this.resets(),
              text: '重置'
            }

          ],
      // 动态组件-表格网格列
      dynamicTableCols:
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableCols.length >
          0
          ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableCols
          : [
            {
              prop: 'billOrderCode',
              label: '结算单号'
            },
            {
              prop: 'dlrCode',
              label: '网点编码'
            },
            {
              prop: 'dlrShortName',
              label: '网点名称'
            },
            {
              prop: 'outOrderCount',
              label: '出库单数量'
            },
            {
              prop: 'billAmount',
              label: '总金额'
            },
            {
              prop: 'billDate',
              label: '结算日期'
            }
          ],

      dynamicButtons1: [],
      dynamicTableCols1: [
        {
          prop: 'outCode',
          label: '出库单号'
        },
        {
          prop: 'outAmount',
          label: '总金额'
        },
        // {
        //   prop: 'optionalPrice',
        //   label: '出库类别'
        // },
        {
          prop: 'createdDate',
          label: '出库日期'
        },
        {
          prop: 'warehouseName',
          label: '分库名称'
        },
        {
          prop: 'costPerson',
          label: '领料人'
        }
      ],
      formField1: {
        billOrderId: ''
      },

      dynamicButtons2: [],
      dynamicTableCols2: [
        {
          prop: 'outCode',
          label: '出库单号'
        },
        {
          prop: 'partNo',
          label: '备件编号'
        },
        {
          prop: 'partName',
          label: '备件名称'
        },
        {
          prop: 'outQty',
          label: '出库数量'
        },
        {
          prop: 'purPrice',
          label: '单价'
        },
        {
          prop: 'outAmount',
          label: '金额'
        }
      ],
      formField2:
        {
          outId: '',
          billOrderId: ''
        },
      // 单表格模版页面组件回调事件
      callbackObj1: {
        // 网格单击事件
        onRowDbClick: (row, column, event) => {
          this.formField1.billOrderId = row.billOrderId || ''
          this.item = row
          this.$refs['multipleTable1'].queryTable(1)
          this.$refs['multipleTable2'].list = []
          this.selectiondata = []
        },
        // 手动勾选网格时，拿到勾选网格的数据
        onCheckSelectChange: (selection, row) => {
          this.selectiondata = selection
          // 计算总价
          // if (selection.length) {
          //   this.calcTotal(selection)
          // } else {
          //   this.item.total = ''
          // }
        }
      },
      callbackObj2: {
        // 网格单击事件
        onRowDbClick: (row, column, event) => {
          // console.log(row);
          this.formField2.outId = row.outId || ''
          this.formField2.billOrderId = row.billOrderId || ''
          this.$refs['multipleTable2'].queryTable(1)
        },
        // 手动勾选网格时，拿到勾选网格的数据
        onCheckSelectChange: (selection, row) => {
          this.selectiondata = selection
          // 计算总价
          if (selection.length) {
            this.calcTotal(selection)
          } else {
            this.item.total = ''
          }
        }
      }
    }
  },
  created() {},
  mounted() {
    this.queryTable(1)
  },
  methods: {
    calcTotal(selection) {
      const totals = selection.reduce((total, o) => {
        return total + Number(o['billAmount'])
      }, 0)
      this.$set(this.item, 'total', totals)
    },
    resetData() {
      this.$refs['multipleTable1'].list = []
      this.$refs['multipleTable2'].list = []
      this.item = {}
      this.selectiondata = []
    },
    unSettlemen() {
      const that = this
      if (!this.selectiondata.length) {
        this.$message('请勾选数据后进行反结算')
      } else {
        const queryObj = {
          apiConfig: orgApis.antiSettlement,
          // 条件/实体参数（变量），根据typeParam中的定义配置
          variables: {
          // 当前中台使用的名称有dataInfo、info，具体查看API文档
            dataInfo: this.selectiondata
          }
        }
        // 转换了中台请求格式数据
        var paramD = that.$getParams(queryObj)
        // 调用中台API方法（可复用）
        that.$requestAPI(paramD).then((response) => {
          if (response.result === '0') return
          if (response.result === '1') {
            that.$message(response.msg || '反结算成功！')
            this.resetData()
            that.queryTable(1)
          } else {
            that.$message(response.msg || '反结算失败！')
          }
        })
      // }
      }
    },
    spanNum() {
      return 12
    },
    // 多表格分开请求
    // queryTableData(formField) {
    //   // // 先读取参数中的传输对象
    //   const returnObj = {
    //   // api配置
    //     apiConfig: api.queryCarConfigLink,
    //     // 条件/实体参数（变量），根据typeParam中的定义配置
    //     variables: formField
    //   }
    //   // 转换了中台请求格式数据
    //   var paramD = this.$getParams(returnObj, null, this.dynamicApiStyle)
    //   // 调用中台API方法（可复用）
    //   this.$requestAPI(paramD, this.dynamicApiStyle).then(response => {
    //     if (response.result === '0') {
    //       // this.$refs['multipleTable'].listLoading = false
    //       if (response.msg) {
    //         this.$message({
    //           message: response.msg,
    //           type: 'warn',
    //           duration: 2000
    //         })
    //       }
    //       return
    //     }
    //     // 返回json
    //     // this.$message({ message: response.msg })
    //     this.$refs['multipleTable1'].list = response.rows.optionalPagList
    //     this.list1 = response.rows.optionalPagList
    //     // this.$refs['multipleTable2'].list = response.rows.colorList
    //     // this.list2 = response.rows.colorList
    //     // this.$refs['multipleTable3'].list = response.rows.inColorList
    //     // this.list3 = response.rows.inColorList
    //     // this.dynamicFieldsData = response.rows[0]
    //   }).catch(err => {
    //     this.message({ message: err })
    //     this.$refs['multipleTable1'].listLoading = false
    //   })
    // },

    // queryTableData2(formField) {
    //   // // 先读取参数中的传输对象
    //   const returnObj = {
    //   // api配置
    //     apiConfig: api.queryCarConfigLink,
    //     // 条件/实体参数（变量），根据typeParam中的定义配置
    //     variables: formField
    //   }
    //   // 转换了中台请求格式数据
    //   var paramD = this.$getParams(returnObj, null, this.dynamicApiStyle)
    //   // 调用中台API方法（可复用）
    //   this.$requestAPI(paramD, this.dynamicApiStyle).then(response => {
    //     if (response.result === '0') {
    //       // this.$refs['multipleTable'].listLoading = false
    //       if (response.msg) {
    //         this.$message({
    //           message: response.msg,
    //           type: 'warn',
    //           duration: 2000
    //         })
    //       }
    //       return
    //     }
    //     // 返回json
    //     // this.$message({ message: response.msg })
    //     this.$refs['multipleTable1'].list = response.rows.optionalPagList
    //     this.list1 = response.rows.optionalPagList
    //     this.$refs['multipleTable2'].list = response.rows.colorList
    //     // this.list2 = response.rows.colorList
    //     // this.$refs['multipleTable3'].list = response.rows.inColorList
    //     // this.list3 = response.rows.inColorList
    //     // this.dynamicFieldsData = response.rows[0]
    //   }).catch(err => {
    //     this.message({ message: err })
    //     this.$refs['multipleTable1'].listLoading = false
    //   })
    // },
    resets() {
      this.reset()
      this.formField.carSeriesCn = ''
      this.formField.carConfigCn = ''
    }
  }
}
</script>
<style lang="css" scoped>
.custom-title{
  margin-bottom: 0;
  padding: 8px 8px 12px;
  background: linear-gradient(to right, #8ebeec, #b6edf3);
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: auto;
  font-size: 14px;
  border-radius: 4px 4px 0 0;
}
.left{
  display: inline-block;
  width: 150px;
}
.blabel {
  font-weight: bold;
}
</style>
